<template>
  <el-dialog title='导出数据到EXCEL' :model-value='modelValue' width='30%' @close='closed'>
    <el-input :placeholder='defaultFileName' v-model='excelFileName'></el-input>
    <template #footer>
      <div class='dialog-footer'>
        <el-button @click='closed'>取消</el-button>
        <el-button type='primary' @click='onConfirm'>确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onActivated } from 'vue'
import { export_json_to_excel } from '~/utils/Export2Excel.js'

const props = defineProps({
  modelValue:{
    type: Boolean,
    required: true
  },
  records: {
    type: Array,
    required: true
  },
  headerMap: {
    type: Object,
    required: true
  },
  defaultFileName: {
    type: String,
    required: true
  }
})

const excelFileName = ref('')
const emits = defineEmits(['update:modelValue'])

onActivated(() => {
  excelFileName.value = props.defaultFileName
})

const closed = () => emits('update:modelValue', false)
const onConfirm = async () => {
  // 将数据数组转换为 excel 可以识别的二维数组
  let list = props.records
  if(!list) throw new Error('没有传入数据无法导出！')

  // 为演示导出为 excel 日期类型转换有问题，手动给每个对象追加日期数据
  list = list.map(item => ({...item, admission_date: '2023-07-08'}))

  // 将父组件传递来的数据列表转换为二维数组
  const excelData = []
  list.forEach(row => {
    let newRecord = []
    for(const key in props.headerMap){
      const fieldName = props.headerMap[key]
      newRecord.push(row[fieldName])
    }
    excelData.push(newRecord)
  })

  const headers = Object.keys(props.headerMap).map(item => item)
  //const excel = await import('~/utils/Export2Excel')// 动态导入
  export_json_to_excel({
    header: headers,
    data: excelData,
    filename: excelFileName.value
  })

  // 关闭文件名模态窗
  closed()
}
</script>